<!DOCTYPE html>
<html lang="en">
  <head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
  <meta content="" name="keywords">

  <title> 杂技浅尝 - </title>
  <meta name="description" content="" />
  <meta property="og:title" content="杂技浅尝" />
  <meta name="twitter:title" content="杂技浅尝" />
  <meta name="author" content="{Description { .Site.Author.name }}"/>
  <meta name="twitter:card" content="summary" />
  <meta property="og:url" content="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/" />
  <meta property="og:type" content="website" />
  <meta property="og:site_name" content="听风的小站" />

  <meta name="generator" content="Hugo 0.67.0" />
  <link rel="canonical" href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/" />
  <link rel="alternate" href="https://systemime.github.io/index.xml" type="application/rss+xml" title="听风的小站">
  <script src="https://res.cloudinary.com/jimmysong/raw/upload/rootsongjc-hugo/jquery-1.12.4.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css" integrity="sha384-wITovz90syo1dJWVh32uuETPVEtGigN07tkttEqPv+uR2SE/mbQcG7ATL28aI9H0" crossorigin="anonymous">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  
  
  <link rel="stylesheet" href="https://systemime.github.io/css/main.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/my.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/pace.css" />
  <link rel="stylesheet" href="https://cdn.plyr.io/3.4.7/plyr.css">
  <link rel="stylesheet" href="https://systemime.github.io/css/lightgallery.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/baguetteBox.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/search.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/reward.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/share.min.css" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" />
  <link rel="stylesheet" href="https://systemime.github.io/css/pygment_highlights.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/highlight.min.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/toc.css" />
  <link rel="stylesheet" href="https://systemime.github.io/css/lightbox.css" />
  <link rel="stylesheet" href="https://systemime.github.io/live2d/css/live2d.css" />
  
  <link href="https://systemime.github.io/css/video-js.css" rel="stylesheet">


<meta name="baidu-site-verification" content="g8IYR9SNLF" />
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?cffe439e37449bb1c07ab26ab56484bb";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>

<link rel="stylesheet" href="https://systemime.github.io/css/prism.css" />









<script src="https://systemime.github.io/js/pace.min.js" data-no-instant></script>



<script src="https://systemime.github.io/js/instantclick.min.js" data-no-instant></script>
   <script data-no-instant>
   InstantClick.on('change', function(isInitialLoad) {
     if (isInitialLoad === false) {
       if (typeof MathJax !== 'undefined') 
         MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
       if (typeof prettyPrint !== 'undefined') 
         prettyPrint();
       if (typeof _hmt !== 'undefined')  
         _hmt.push(['_trackPageview', location.pathname + location.search]);
       if (typeof ga !== 'undefined')  
           ga('send', 'pageview', location.pathname + location.search);
     }
   });
   InstantClick.init();
</script>




<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/gist-embed/2.7.1/gist-embed.min.js"></script>


<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
  (adsbygoogle = window.adsbygoogle || []).push({
    google_ad_client: "ca-pub-3925981084585036",
    enable_page_level_ads: true
  });
</script>



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/photoswipe.min.css" integrity="sha256-sCl5PUOGMLfFYctzDW3MtRib0ctyUvI9Qsmq2wXOeBY=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/default-skin/default-skin.min.css" integrity="sha256-BFeI1V+Vh1Rk37wswuOYn5lsTcaU96hGaI7OUVCLjPc=" crossorigin="anonymous" />



<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

<div class="pswp__bg"></div>

<div class="pswp__scroll-wrap">
    
    <div class="pswp__container">
      <div class="pswp__item"></div>
      <div class="pswp__item"></div>
      <div class="pswp__item"></div>
    </div>
    
    <div class="pswp__ui pswp__ui--hidden">
    <div class="pswp__top-bar">
      
      <div class="pswp__counter"></div>
      <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
      <button class="pswp__button pswp__button--share" title="Share"></button>
      <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
      <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
      
      
      <div class="pswp__preloader">
        <div class="pswp__preloader__icn">
          <div class="pswp__preloader__cut">
            <div class="pswp__preloader__donut"></div>
          </div>
        </div>
      </div>
    </div>
    <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
      <div class="pswp__share-tooltip"></div>
    </div>
    <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
    </button>
    <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
    </button>
    <div class="pswp__caption">
      <div class="pswp__caption__center"></div>
    </div>
    </div>
    </div>
</div>

</head>

  <body>
    <nav class="navbar navbar-default navbar-fixed-top navbar-custom">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="https://systemime.github.io">听风的小站</a>
    </div>
    <div class="collapse navbar-collapse" id="main-navbar">
      <ul class="nav navbar-nav navbar-right">
        
          
            <li>
		    <a title="博客" href="https://systemime.github.io/blog/">博客</a>
              
              
            </li>
          
        
          
            <li>
		    <a title="片刻" href="https://systemime.github.io/moment/">片刻</a>
              
              
            </li>
          
        
          
            <li>
		    <a title="关于" href="https://systemime.github.io/about/">关于</a>
              
              
            </li>
          
        
          
            <li>
		    <a title="留言" href="https://systemime.github.io/message/">留言</a>
              
              
            </li>
          
        

        

        
        
      </ul>
    </div>

    <div class="avatar-container">
      <div class="avatar-img-border">
        
      </div>
    </div>

  </div>
</nav>






    
  <header class="header-section ">
    <div class="intro-header no-img">
      <div class="container">
        <div class="row">
          <div class="col-lg-12 col-md-12 col-md-offset-0">
            <div class="page-heading">
              <h1>#杂技浅尝</h1>
              <hr class="small">
            </div>
          </div>
        </div>
      </div>
    </div>
  </header>

    
  <div class="container" role="main">
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        
        <div class="posts-list">
          
            <article class="post-preview">
              <a href="https://systemime.github.io/blog/2019-05/go%E5%9F%BA%E7%A1%80-%E7%A8%8B%E5%BA%8F%E5%AE%9E%E4%BD%93%E8%A1%A5%E5%85%85/">
                <h2 class="post-title">Go基础---程序实体补充</h2>

                
              </a>

              <p class="post-meta">
                Posted on May 15, 2019
              </p>
              <div class="post-entry">
                
                  <h2 id="一如何判断变量类型">一、如何判断变量类型</h2>
<p>断言</p>
<p>下面是例子代码：</p>
<div class="highlight"><pre class="chroma"><code class="language-go" data-lang="go"><span class="kn">import</span> <span class="p">(</span>
    <span class="s">&#34;fmt&#34;</span>
<span class="p">)</span>
<span class="kd">func</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">name</span> <span class="p">=</span> <span class="s">&#34;icode&#34;</span>
    <span class="nx">value</span><span class="p">,</span> <span class="nx">ok</span> <span class="o">:=</span> <span class="kd">interface</span><span class="p">{}(</span><span class="nx">name</span><span class="p">).(</span><span class="kt">string</span><span class="p">)</span>
    <span class="nx">fmt</span><span class="p">.</span><span class="nf">Println</span><span class="p">(</span><span class="nx">value</span><span class="p">)</span>
    <span class="nx">fmt</span><span class="p">.</span><span class="nf">Println</span><span class="p">(</span><span class="nx">ok</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div><p><strong>注意：类型断言的时候我们必须先转换为接口类型</strong></p>
<ul>
<li>
<p>在Go语言中interace{} 代表空接口，任何类型都是它的实现类型</p>
</li>
<li>
<p>一对不包含任何东西的花括号，除了可以代表空的代码块之外，还可以用于表示不包含任何内容的数据结构（或者说数据类型）</p>
</li>
<li>
<p>如：<code>struct{}</code>，它就代表了不包含任何字段和方法的、空的结构体类型</p>
</li>
<li>
<p>空接口<code>interface{}</code>则代表了不包含任何方法定义的、空接口类型</p>
</li>
<li>
<p>字面量：用来表示数据类型本身的若干个字符</p>
</li>
</ul>
<h2 id="二关于string类型和各种切片类型的互转">二、关于string类型和各种切片类型的互转</h2>
<ul>
<li>
<p>一个值从string类型向<code>[]byte</code>类型转换时代表<code>UTF-8</code>编码的字符串被拆分成独立的字节</p>
</li>
<li>
<p>一个值从string类型向<code>[]rune </code>类型转换的时候代表着字符串会被拆分成一个个<code>Unicode</code>字符</p>
</li>
</ul>
<h2 id="三别名类型vs-潜在类型">三、别名类型VS 潜在类型</h2>
<p>我们可以通过下面方式声明：</p>
<div class="highlight"><pre class="chroma"><code class="language-go" data-lang="go"><span class="kd">type</span> <span class="nx">MyString</span> <span class="p">=</span> <span class="kt">string</span>
</code></pre></div><p>这样<code>MyString</code> 就是<code>string</code>类型的别名类型</p>
<p>在Go内建的基本类型中就存在两个别名类型：byte是uint8的别名类型，而rune是int32的别名类型</p>
<p>而下面这种声明方式：</p>
<pre><code>type MyString string
</code></pre><p>这里MyString和string就不是一种类型了，这种方式叫做对类型的再定义</p>
<p>我们可以把string是MyString的潜在类型</p>
<p>潜在类型的含义：某个类型在本质上是哪个类型，或者是哪个类型的集合。</p>
<p>如果两个值的潜在类型相同，却属于不同的类型，它们之间是可以做类型转换的。但是它们的值不能进行判断等或比较，它们变量之间不能赋值</p>

                
              </div>

              
                <span class="post-meta">
                  
                    #<a href="https://systemime.github.iotags/go/">Go</a>&nbsp;
                  
                    #<a href="https://systemime.github.iotags/%E8%A1%A5%E5%85%85/">补充</a>&nbsp;
                  
                </span>
              

            </article>
          
            <article class="post-preview">
              <a href="https://systemime.github.io/blog/2019-05/go%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80%E8%AF%AD%E6%B3%95/">
                <h2 class="post-title">Go语言基础语法</h2>

                
              </a>

              <p class="post-meta">
                Posted on May 15, 2019
              </p>
              <div class="post-entry">
                
                  <h2 id="hello-world">Hello world</h2>
<div class="highlight"><pre class="chroma"><code class="language-go" data-lang="go"><span class="kn">package</span> <span class="nx">main</span>
<span class="c1">// 程序入口
</span><span class="c1"></span><span class="kn">import</span> <span class="s">&#34;fmt&#34;</span>
<span class="c1">// 输出库
</span><span class="c1"></span><span class="kd">func</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// 主程序入口
</span><span class="c1"></span>	<span class="nx">fmt</span><span class="p">.</span><span class="nf">Print</span><span class="p">(</span><span class="s">&#34;hello world&#34;</span><span class="p">)</span>
	<span class="c1">// 输出语句
</span><span class="c1"></span><span class="p">}</span>
</code></pre></div><h2 id="变量">变量</h2>
<p><strong>在go语言中，凡是定义的变量必须使用，否则会报错</strong></p>
<h3 id="变量定义方法">变量定义方法</h3>
<blockquote>
<p>var a int</p>
</blockquote>
<p>在go语言中，一般定义变量使用关键字<code>var</code>，在go语言中，变量名写在前，变量类型在后</p>
<div class="highlight"><pre class="chroma"><code class="language-go" data-lang="go"><span class="kd">func</span> <span class="nf">variable</span><span class="p">()</span>  <span class="p">{</span> <span class="c1">// go语言函数写法，在后面会说明，此处先看内容
</span><span class="c1"></span>	<span class="kd">var</span> <span class="nx">a</span> <span class="kt">int</span>
	<span class="kd">var</span> <span class="nx">s</span> <span class="kt">string</span>
	<span class="nx">fmt</span><span class="p">.</span><span class="nf">Printf</span><span class="p">(</span><span class="s">&#34;variable()输出：%d %q\n&#34;</span><span class="p">,</span><span class="nx">a</span><span class="p">,</span><span class="nx">s</span><span class="p">)</span>
	<span class="c1">// %q可以输出空字符串
</span><span class="c1"></span>	<span class="p">}</span>
</code></pre></div><p>在go语言中s是空字符串，而不是<code>null</code>，这在go语言中也是不存在<code>null</code>的，是<code>nil</code></p>
<h3 id="变量赋值">变量赋值</h3>
<div class="highlight"><pre class="chroma"><code class="language-go" data-lang="go"><span class="kd">func</span> <span class="nf">variableInitialValue</span><span class="p">(){</span>
	<span class="kd">var</span> <span class="nx">a</span><span class="p">,</span><span class="nx">b</span> <span class="kt">int</span> <span class="p">=</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span>
	<span class="kd">var</span> <span class="nx">s</span> <span class="kt">string</span> <span class="p">=</span> <span class="s">&#34;abc&#34;</span>
	<span class="nx">fmt</span><span class="p">.</span><span class="nf">Printf</span><span class="p">(</span><span class="s">&#34;%d %q %d\n&#34;</span><span class="p">,</span><span class="nx">a</span><span class="p">,</span><span class="nx">s</span><span class="p">,</span><span class="nx">b</span><span class="p">)</span>
	<span class="c1">// 直接输出
</span><span class="c1"></span>	<span class="nx">fmt</span><span class="p">.</span><span class="nf">Println</span><span class="p">(</span><span class="nx">a</span><span class="p">,</span><span class="nx">s</span><span class="p">,</span><span class="nx">b</span><span class="p">)</span>
	<span class="c1">// 带换行的输出
</span><span class="c1"></span><span class="p">}</span>
</code></pre></div><p>go语言中可以直接赋多个值，在多个变量时，也可以省去书写多个var的麻烦，如:</p>
<div class="highlight"><pre class="chroma"><code class="language-go" data-lang="go"><span class="kd">var</span> <span class="p">(</span><span class="c1">//省去多次书写var的麻烦
</span><span class="c1"></span>	<span class="nx">aaa</span><span class="p">=</span><span class="mi">3</span>
	<span class="nx">sss</span><span class="p">=</span><span class="s">&#34;kkk&#34;</span>
	<span class="nx">bb</span><span class="p">=</span><span class="kc">true</span>
	<span class="c1">// bool类型
</span><span class="c1"></span><span class="p">)</span>
</code></pre></div><p>当然，你也可以让go语言<strong>自动识别变量类型</strong>，并同时赋值多个变量</p>
<div class="highlight"><pre class="chroma"><code class="language-go" data-lang="go"><span class="kd">func</span> <span class="nf">variableType</span><span class="p">(){</span>
	<span class="kd">var</span> <span class="nx">a</span><span class="p">,</span><span class="nx">b</span><span class="p">,</span><span class="nx">c</span><span class="p">,</span><span class="nx">d</span> <span class="p">=</span> <span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="kc">true</span><span class="p">,</span><span class="s">&#34;def&#34;</span>
	<span class="nx">fmt</span><span class="p">.</span><span class="nf">Println</span><span class="p">(</span><span class="nx">a</span><span class="p">,</span><span class="nx">b</span><span class="p">,</span><span class="nx">c</span><span class="p">,</span><span class="nx">d</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div><p>如果你连var都不想写了，当然也是可以的</p>
<div class="highlight"><pre class="chroma"><code class="language-go" data-lang="go"><span class="kd">func</span> <span class="nf">variableShort</span><span class="p">(){</span>
	<span class="nx">a</span><span class="p">,</span><span class="nx">b</span><span class="p">,</span><span class="nx">c</span><span class="p">,</span><span class="nx">d</span> <span class="o">:=</span> <span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="kc">true</span><span class="p">,</span><span class="s">&#34;def&#34;</span>
	<span class="c1">//e:=5 //再使用会报错,只能第一次使用
</span><span class="c1"></span>	<span class="nx">fmt</span><span class="p">.</span><span class="nf">Println</span><span class="p">(</span><span class="nx">a</span><span class="p">,</span><span class="nx">b</span><span class="p">,</span><span class="nx">c</span><span class="p">,</span><span class="nx">d</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div><p>但是要注意，在一段代码中<code>:=</code>的赋值方式只能使用一次，如果再使用，则会报错</p>
<p>还有一点要注意的是，在定义全局变量时（实际上go语言没有全局变量说法，只有<code>包变量</code>）</p>
<p>同时，go语言在定义全局变量时，不允许使用<code>:=</code>的方式进行赋值</p>
<div class="highlight"><pre class="chroma"><code class="language-go" data-lang="go"><span class="kn">package</span> <span class="nx">main</span>
<span class="kn">import</span> <span class="p">(</span>
	<span class="s">&#34;fmt&#34;</span>
<span class="p">)</span>
<span class="c1">//需要导入多个库写法
</span><span class="c1"></span>
<span class="kd">var</span> <span class="nx">aa</span> <span class="p">=</span> <span class="mi">3</span>
<span class="kd">var</span> <span class="nx">ss</span><span class="p">=</span><span class="s">&#34;kkk&#34;</span>
<span class="c1">// 没有全局变量说法，只是包变量
</span><span class="c1">// bb:=true
</span><span class="c1">// 不能在全局用:=，必须用var
</span><span class="c1"></span>
<span class="kd">func</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
	<span class="nx">fmt</span><span class="p">.</span><span class="nf">Println</span><span class="p">(</span><span class="nx">aa</span><span class="p">,</span> <span class="nx">ss</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div><p>go语言与其他语言不同的地方在于它<strong>支持复数</strong>，具体使用方法见代码注释</p>
<div class="highlight"><pre class="chroma"><code class="language-go" data-lang="go"><span class="kn">package</span> <span class="nx">main</span>
<span class="kn">import</span> <span class="p">(</span>
	<span class="s">&#34;fmt&#34;</span>
	<span class="s">&#34;math/cmplx&#34;</span>
<span class="p">)</span>
<span class="kd">func</span> <span class="nf">euler</span><span class="p">(){</span>
	<span class="nx">c</span><span class="o">:=</span><span class="mi">3</span><span class="o">+</span><span class="m">4i</span> <span class="c1">//复数类型不能用4*i，会误以为i是变量
</span><span class="c1"></span>	<span class="nx">fmt</span><span class="p">.</span><span class="nf">Println</span><span class="p">(</span><span class="nx">cmplx</span><span class="p">.</span><span class="nf">Abs</span><span class="p">(</span><span class="nx">c</span><span class="p">),)</span>
	<span class="nx">fmt</span><span class="p">.</span><span class="nf">Printf</span><span class="p">(</span><span class="s">&#34;%.3f\n&#34;</span><span class="p">,</span><span class="nx">cmplx</span><span class="p">.</span><span class="nf">Exp</span><span class="p">(</span><span class="m">1i</span> <span class="o">*</span> <span class="nx">math</span><span class="p">.</span><span class="nx">Pi</span><span class="p">)</span><span class="o">+</span><span class="mi">1</span><span class="p">)</span> <span class="c1">//1i为了让系统知道i是个复数，不是变量
</span><span class="c1"></span><span class="p">}</span>
<span class="kd">func</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
	<span class="nf">euler</span><span class="p">()</span>
<span class="p">}</span>

<span class="cm">/* -----------输出-------------- */</span>

    <span class="mi">5</span>
    <span class="p">(</span><span class="mf">0.000</span><span class="o">+</span><span class="m">0.000i</span><span class="p">)</span>

<span class="cm">/* -----------输出-------------- */</span>
</code></pre></div><p>交换变量时，go可以像python一样，直接将两个变量交换</p>
<pre><code>a, b = b, a
</code></pre><h3 id="常量与类型转换">常量与类型转换</h3>
<p>在go语言中，任何涉及的类型转换的地方都<strong>必须使用显示类型转换</strong></p>
<pre><code>func triangle(){
	a,b:=3,4
	var c int //go语言只能强制类型转换，没有隐式的，所以int（）之类不能省
	c = int(math.Sqrt(float64(a*a+b*b)))
	fmt.Println(c)
	//由于float有时候不准，所以这条式子有可能是4
	//该问题存在于任何编程语言中
}
</code></pre><p>以求勾股定理代码为例，<code>math.Sqrt()</code>要求以float64为输入类型，而求得的c要求以整形</p>
<p>有这么一种情况可能在实际编写的过程中被认为存在类型转换，实际上并没有，也不是所谓的隐式类型转换</p>
<div class="highlight"><pre class="chroma"><code class="language-go" data-lang="go"><span class="kd">func</span> <span class="nf">consts</span><span class="p">(){</span>
	<span class="kd">const</span><span class="p">(</span>
		<span class="nx">filename</span> <span class="kt">string</span> <span class="p">=</span> <span class="s">&#34;abc.txt&#34;</span>
		<span class="nx">a</span><span class="p">,</span><span class="nx">b</span><span class="p">=</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span>
	<span class="p">)</span>
	<span class="c1">// go语言中常量的写法
</span><span class="c1"></span>	<span class="cm">/*关于常量，go语言中常量书写方式一般不大写，因为在go中首字母大写有其他含义日后学习中再总结*/</span>
	
	<span class="kd">var</span> <span class="nx">c</span> <span class="kt">int</span>
	<span class="nx">c</span> <span class="p">=</span> <span class="nb">int</span><span class="p">(</span><span class="nx">math</span><span class="p">.</span><span class="nf">Sqrt</span><span class="p">(</span><span class="nx">a</span><span class="o">*</span><span class="nx">a</span><span class="o">+</span><span class="nx">b</span><span class="o">*</span><span class="nx">b</span><span class="p">))</span>
	
	<span class="c1">//上面定义未指定a，b类型，可以是int也可以是float
</span><span class="c1"></span>	<span class="c1">// 所以在上面不需要显示转换，被认为是float64
</span><span class="c1"></span>	
	<span class="nx">fmt</span><span class="p">.</span><span class="nf">Println</span><span class="p">(</span><span class="nx">filename</span><span class="p">,</span><span class="nx">c</span><span class="p">)</span>
<span class="p">}</span>

<span class="cm">/* -----------输出-------------- */</span>

    <span class="nx">abc</span><span class="p">.</span><span class="nx">txt</span> <span class="mi">5</span>

<span class="cm">/* -----------输出-------------- */</span>
	
</code></pre></div><h2 id="if与switch">if与switch</h2>
<p>在go语言中，它的if与switch写法与其他语言在一般的写法上没有什么太大区别，增加了一些特色的写法，如可以在if后面执行一条语句，</p>
<h3 id="if写法">if写法</h3>
<p>以这段代码为例子，代码中的<code>nil</code>可以看这篇文章<a href="https://qfdxz.top/2019/02/11/Golang%E4%B9%8Bnil/">Golang之nil</a>讲解相对详细，在此不废话</p>
<pre><code>package main

import (
	&quot;fmt&quot;
	&quot;io/ioutil&quot;
)
func iftext(){
	const filename = &quot;abc.txt&quot;
	// windows有时可以使用绝对路径如：F:\\GO_S\\stury001\\src\\abc.txt
	
	contents, err := ioutil.ReadFile(filename)
	/* go返回值有两个
	   第一个返回值是正常的返回值
	   第二个返回值err通常作为程序状态返回信息 */
	/* 该方法时go语言读取文件内容，如果文件不存在时err获取到错误信息 */
	/* 文件存在时读取文件内容 */
	if err != nil {
		fmt.Println(err)
	}else{
		fmt.Printf(&quot;%s\n&quot;,contents)
	}
	
	//特色写法
	if contents2, err2 := ioutil.ReadFile(filename);err2 !=nil {
		fmt.Println(err)
	}else{
		fmt.Printf(&quot;%s\n&quot;,contents2)
	}
	//fmt.Println(contents2)
	// 这句话会报错，因为contents2生存期只在特色写法的if中存在
}

func iftext2(){
	if a:= 1==1; a{
		fmt.Println(&quot;1==1&quot;)
	}
}

func main() {
	fmt.Println()
	iftext()
	iftext2()
}

/* -----------输出-------------- */

    文件不存在时：open abc.txt: The system cannot find the file specified.
	
	文件存在时：文件内容

/* -----------输出-------------- */
</code></pre><p><strong>注意</strong></p>
<ul>
<li>if判断条件没有括号</li>
<li>if语句后面必须有<code>{}</code>，无论下面几句话</li>
<li>else必须<strong>紧跟</strong>在if的{}后</li>
<li>else后面也必须有<code>{}</code>,无论下面几句话</li>
</ul>
<h3 id="switch写法">switch写法</h3>
<pre><code>package main

import (
	&quot;fmt&quot;
)

func grade(score int) string {
	g :=&quot;&quot;
	switch {
	case score&lt;60:
		g=&quot;F&quot;
	case score&lt;80:
		g=&quot;C&quot;
	case score&lt;90:
		g=&quot;B&quot;
	case score&lt;=100:
		g=&quot;A&quot;
	default:
		panic(fmt.Sprintf(&quot;Wrong score:%d&quot;,score))
	}
	return g
}

func grade2(){
	for i:=0;i&lt;5;i++{
		switch i{
		//此处i可以做运算，如i%2==0
			case 0, 2:
				fmt.Println(&quot;Even&quot;)
			case 0, 2:
				fmt.Println(&quot;0dd&quot;)
			defaule:
				fmt.Println(&quot;it is not &quot;)
		}
	}
}

func main() {
	fmt.Println()
	fmt.Println(
		grade(0),
		grade(59),
		grade(60),
		grade(82),
		grade(100),
		)//若输入错误，整个程序中断，
		// 输出default中内容，同时不显示其他参数执行结果
}

/* -----------输出-------------- */

    F F C B A

/* -----------输出-------------- */
</code></pre><h2 id="枚举">枚举</h2>
<p>这部分直接看样例代码与输出</p>
<pre><code>package main
//day2  常量与枚举
import (
	&quot;fmt&quot;
	&quot;math&quot;
)
const filename1 = &quot;123.txt&quot;//常量也可以在包内定义

func enums1()  {//go没有特殊枚举关键字，一般用一组const
	const( //const必须给其赋值
		cpp = 0
		java = 1
		python = 3
		golang = 5
	)
	const(//const高级用法
		b = 1&lt;&lt;(10*iota)  //移位，下面变量全部使用该公式，结果递增
		kb
		mb
		gb
		tb
		pb
	)
	fmt.Println(cpp,java,python,golang)
	fmt.Println(b,kb,mb,gb,tb,pb)
}
func enums2()  {
	const( //const自增属性
		cpp = iota //若直接cpp=1，则const内所有变量均为1
		//自增顺序以const组中变量书写顺序为准（0开始）
		java
		python
		golang
	)
	fmt.Println(cpp,java,python,golang)
}
func main() {
	fmt.Println(filename1)//输出全局常量
	enums1()
	enums2()
}

/* -----------输出-------------- */

    123.txt
	
	enums1()输出：
	0 1 3 5
	1 1024 1048576 1073741824 1099511627776 1125899906842624
	
	enums2()输出：
	0 1 2 3

/* -----------输出-------------- */
</code></pre><h2 id="循环">循环</h2>
<p>在go语言中，仅支持循环关键字<code>for</code>, 没有<code>while</code>循环，<code>while</code>被<code>for</code>的不同写法代替</p>
<ul>
<li>条件循环</li>
</ul>
<div class="highlight"><pre class="chroma"><code class="language-go" data-lang="go"><span class="nx">n</span> <span class="o">:=</span> <span class="mi">0</span>
<span class="k">for</span> <span class="nx">n</span><span class="p">&lt;</span><span class="mi">5</span><span class="p">{</span>
	<span class="nx">n</span><span class="o">++</span>
	<span class="nx">fmt</span><span class="p">.</span><span class="nf">Printf</span><span class="p">(</span><span class="nx">n</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div><ul>
<li>无限循环</li>
</ul>
<pre><code>n:=0
for {
	...
}
</code></pre><ul>
<li>for循环</li>
</ul>
<pre><code>for(j:=7; j&lt;=9 ;j++){
	...
}
</code></pre>
                
              </div>

              
                <span class="post-meta">
                  
                    #<a href="https://systemime.github.iotags/go/">Go</a>&nbsp;
                  
                    #<a href="https://systemime.github.iotags/%E5%9F%BA%E7%A1%80/">基础</a>&nbsp;
                  
                </span>
              

            </article>
          
            <article class="post-preview">
              <a href="https://systemime.github.io/blog/2019-05/django%E5%B8%B8%E7%94%A8%E8%AF%AD%E6%B3%95/">
                <h2 class="post-title">Django——常用语法</h2>

                
              </a>

              <p class="post-meta">
                Posted on May 12, 2019
              </p>
              <div class="post-entry">
                
                  <h2 id="官方文档">官方文档</h2>
<p><a href="https://docs.djangoproject.com/zh-hans/2.2/ref/templates/builtins/">Django2.2</a></p>
<h2 id="常用语法">常用语法</h2>
<p>只需要记两种特殊符号：</p>
<pre><code>{{}} 和 {%%}

变量相关的用
{{}}

逻辑相关的用
{%%}
</code></pre><h3 id="变量">变量</h3>
<p>在Django的模板语言中按此语法使用：<code>{{ 变量名 }}</code>。</p>
<p>当模版引擎遇到一个变量，它将计算这个变量，然后用结果替换掉它本身。 变量的命名包括任何字母数字以及下划线 <code>_</code> 的组合。 变量名称中不能有空格或标点符号。</p>
<p>点 <code>.</code> 在模板语言中有特殊的含义。当模版系统遇到点 <code>.</code> ，它将以这样的顺序查询：</p>
<ul>
<li>字典查询（Dictionary lookup）</li>
<li>属性或方法查询（Attribute or method lookup）</li>
<li>数字索引查询（Numeric index lookup）</li>
</ul>
<p><strong>注意事项：</strong></p>
<ol>
<li>如果计算结果的值是可调用的，它将被无参数的调用。 调用的结果将成为模版的值。</li>
<li>如果使用的变量不存在， 模版系统将插入 <code>string_if_invalid</code> 选项的值， 它被默认设置为&rsquo;&rsquo; (空字符串) 。
几个例子：</li>
</ol>
<p>view中代码：</p>
<pre><code>def template_test(request):
    l = [11, 22, 33]
    d = {&quot;name&quot;: &quot;alex&quot;}

    class Person(object):
        def __init__(self, name, age):
            self.name = name
            self.age = age

        def dream(self):
            return &quot;{} is dream...&quot;.format(self.name)

    Alex = Person(name=&quot;Alex&quot;, age=34)
    Egon = Person(name=&quot;Egon&quot;, age=9000)
    Eva_J = Person(name=&quot;Eva_J&quot;, age=18)

    person_list = [Alex, Egon, Eva_J]
    return render(request, &quot;template_test.html&quot;, {&quot;l&quot;: l, &quot;d&quot;: d, &quot;person_list&quot;: person_list})
</code></pre><p>模板中支持的写法：</p>
<pre><code>{# 取l中的第一个参数 #}
{{ l.0 }}
{# 取字典中key的值 #}
{{ d.name }}
{# 取对象的name属性 #}
{{ person_list.0.name }}
{# .操作只能调用不带参数的方法 #}
{{ person_list.0.dream }}
</code></pre><h3 id="filters过滤器">Filters（过滤器）</h3>
<p>在Django的模板语言中，通过使用 <code>过滤器</code> 来改变变量的显示。</p>
<p>过滤器的语法：</p>
<pre><code>{{ value|filter_name:参数 }}
</code></pre><p>使用管道符 <code>|</code> 来应用过滤器。</p>
<p>例如：</p>
<pre><code>{{ name|lower }}

会将name变量应用lower过滤器之后再显示它的值。lower在这里的作用是将文本全都变成小写。
</code></pre><p><strong>注意事项：</strong></p>
<ol>
<li>过滤器支持“链式”操作。即一个过滤器的输出作为另一个过滤器的输入。</li>
<li>过滤器可以接受参数，例如：</li>
</ol>
<pre><code>{{ sss|truncatewords:30 }}
# 这将显示sss的前30个词。
</code></pre><ol start="3">
<li>过滤器参数包含空格的话，必须用引号包裹起来。比如使用逗号和空格去连接一个列表中的元素，如：</li>
</ol>
<pre><code>{{ list|join:', ' }}
</code></pre><ol start="4">
<li><code>|</code> 左右没有空格没有空格没有空格</li>
</ol>
<p><strong>Django的模板语言中提供了大约六十个内置过滤器。</strong></p>
<h4 id="default">default</h4>
<p><strong>如果一个变量是false或者为空，使用给定的默认值。 否则，使用变量的值。</strong></p>
<pre><code>{{ value|default:&quot;nothing&quot;}}
</code></pre><p>如果value没有传值或者值为空的话就显示nothing</p>
<h4 id="length">length</h4>
<p><strong>返回值的长度，作用于字符串和列表。</strong></p>
<pre><code>{{ value|length }}
</code></pre><p>返回value的长度，如 <code>value=['a', 'b', 'c', 'd']</code>的话，就显示4.</p>
<h4 id="filesizeformat">filesizeformat</h4>
<p>将值格式化为一个 “人类可读的” 文件尺寸 （例如 <code>13 KB</code>, <code>4.1 MB</code>, <code>102 bytes</code>, 等等）。例如：</p>
<pre><code>{{ value|filesizeformat }}
</code></pre><p>如果 value 是 123456789，输出将会是 117.7 MB。</p>
<h4 id="slice">slice</h4>
<p>切片</p>
<pre><code>{{value|slice:&quot;2:-1&quot;}}
</code></pre><p>与python中切片几乎无异议</p>
<h4 id="date">date</h4>
<p>格式化</p>
<pre><code>{{ value|date:&quot;Y-m-d H:i:s&quot;}}
</code></pre><p>可用的参数：</p>
<table>
<thead>
<tr>
<th align="center">格式化字符</th>
<th align="center">描述</th>
<th align="center">示例输出</th>
</tr>
</thead>
<tbody>
<tr>
<td align="center">a</td>
<td align="center"><code>a.m.</code>或<code>p.m.</code>（请注意，这与PHP的输出略有不同，因为这包括符合Associated Press风格的期间）</td>
<td align="center"><code>a.m.</code></td>
</tr>
<tr>
<td align="center">A</td>
<td align="center"><code>AM</code>或<code>PM</code></td>
<td align="center"><code>AM</code></td>
</tr>
<tr>
<td align="center">b</td>
<td align="center">月，文字，3个字母，小写</td>
<td align="center"><code>jan</code></td>
</tr>
<tr>
<td align="center">B</td>
<td align="center">未实现。</td>
<td align="center"></td>
</tr>
<tr>
<td align="center">c</td>
<td align="center">ISO 8601格式。 （注意：与其他格式化程序不同，例如“Z”，“O”或“r”，如果值为naive datetime，则“c”格式化程序不会添加时区偏移量（请参阅<code>[datetime.tzinfo](https://docs.python.org/3/library/datetime.html#datetime.tzinfo)</code>）</td>
<td align="center">2008-01-02T10:30:00.000123+02:00或2008-01-02T10:30:00.000123如果datetime是天真的</td>
</tr>
<tr>
<td align="center">d</td>
<td align="center">月的日子，带前导零的2位数字</td>
<td align="center"><code>01</code>到<code>31</code></td>
</tr>
<tr>
<td align="center">D</td>
<td align="center">一周中的文字，3个字母</td>
<td align="center"><code>“星期五”</code></td>
</tr>
<tr>
<td align="center">e</td>
<td align="center">时区名称 可能是任何格式，或者可能返回一个空字符串，具体取决于datetime</td>
<td align="center"><code>''</code>、<code>'GMT'</code>、<code>'-500'</code>、<code>'US/Eastern'</code>等</td>
</tr>
<tr>
<td align="center">E</td>
<td align="center">月份，特定地区的替代表示通常用于长日期表示</td>
<td align="center"><code>'listopada'</code>（对于波兰语区域，而不是<code>'Listopad'</code>）</td>
</tr>
<tr>
<td align="center">f</td>
<td align="center">时间，在12小时的小时和分钟内，如果它们为零，则分钟停留。专有扩展</td>
<td align="center"><code>'1'</code>，<code>'1:30'</code></td>
</tr>
<tr>
<td align="center">F</td>
<td align="center">月，文，长</td>
<td align="center"><code>'一月'</code></td>
</tr>
<tr>
<td align="center">g</td>
<td align="center">小时，12小时格式，无前导零</td>
<td align="center"><code>'1'</code>到<code>'12'</code></td>
</tr>
<tr>
<td align="center">G</td>
<td align="center">小时，24小时格式，无前导零</td>
<td align="center"><code>'0'</code>到<code>'23'</code></td>
</tr>
<tr>
<td align="center">h</td>
<td align="center">小时，12小时格式</td>
<td align="center"><code>'01'</code>到<code>'12'</code></td>
</tr>
<tr>
<td align="center">H</td>
<td align="center">小时，24小时格式</td>
<td align="center"><code>'00'</code>到<code>'23'</code></td>
</tr>
<tr>
<td align="center">i</td>
<td align="center">分钟</td>
<td align="center"><code>'00'</code>到<code>'59'</code></td>
</tr>
<tr>
<td align="center">I</td>
<td align="center">夏令时间，无论是否生效</td>
<td align="center"><code>'1'</code>或<code>'0'</code></td>
</tr>
<tr>
<td align="center">j</td>
<td align="center">没有前导零的月份的日子</td>
<td align="center"><code>'1'</code>到<code>'31'</code></td>
</tr>
<tr>
<td align="center">l</td>
<td align="center">星期几，文字长</td>
<td align="center"><code>'星期五'</code></td>
</tr>
<tr>
<td align="center">L</td>
<td align="center">布尔值是否是一个闰年</td>
<td align="center"><code>True</code>或<code>False</code></td>
</tr>
<tr>
<td align="center">m</td>
<td align="center">月，2位数字带前导零</td>
<td align="center"><code>'01'</code>到<code>'12'</code></td>
</tr>
<tr>
<td align="center">M</td>
<td align="center">月，文字，3个字母</td>
<td align="center"><code>“扬”</code></td>
</tr>
<tr>
<td align="center">n</td>
<td align="center">月无前导零</td>
<td align="center"><code>'1'</code>到<code>'12'</code></td>
</tr>
<tr>
<td align="center">N</td>
<td align="center">美联社风格的月份缩写。 专有扩展</td>
<td align="center"><code>'Jan.'</code>，<code>'Feb.'</code>，<code>'March'</code>，<code>'May'</code></td>
</tr>
<tr>
<td align="center">o</td>
<td align="center">ISO-8601周编号，对应于使用闰年的ISO-8601周数（W） 对于更常见的年份格式，请参见Y</td>
<td align="center"><code>'1999年'</code></td>
</tr>
<tr>
<td align="center">O</td>
<td align="center">与格林威治时间的差异在几小时内</td>
<td align="center"><code>'+0200'</code></td>
</tr>
<tr>
<td align="center">P</td>
<td align="center">时间为12小时，分钟和&rsquo;a.m。'/&lsquo;p.m。'，如果为零，分钟停留，特殊情况下的字符串“午夜”和“中午”。 专有扩展</td>
<td align="center"><code>'1 am'</code>，<code>'1:30 pm' / t3&gt;，'midnight'，'noon'，'12：30 pm' / T10&gt;</code></td>
</tr>
<tr>
<td align="center">r</td>
<td align="center">RFC 5322格式化日期</td>
<td align="center"><code>'Thu, 21 Dec 2000 16:01:07 +0200'</code></td>
</tr>
<tr>
<td align="center">s</td>
<td align="center">秒，带前导零的2位数字</td>
<td align="center"><code>'00'</code>到<code>'59'</code></td>
</tr>
<tr>
<td align="center">S</td>
<td align="center">一个月的英文序数后缀，2个字符</td>
<td align="center"><code>'st'</code>，<code>'nd'</code>，<code>'rd'</code>或<code>'th'</code></td>
</tr>
<tr>
<td align="center">t</td>
<td align="center">给定月份的天数</td>
<td align="center"><code>28</code> to <code>31</code></td>
</tr>
<tr>
<td align="center">T</td>
<td align="center">本机的时区</td>
<td align="center"><code>'EST'</code>，<code>'MDT'</code></td>
</tr>
<tr>
<td align="center">u</td>
<td align="center">微秒</td>
<td align="center"><code>000000</code> to <code>999999</code></td>
</tr>
<tr>
<td align="center">U</td>
<td align="center">自Unix Epoch以来的二分之一（1970年1月1日00:00:00 UTC）</td>
<td align="center"></td>
</tr>
<tr>
<td align="center">w</td>
<td align="center">星期几，数字无前导零</td>
<td align="center"><code>'0'</code>（星期日）至<code>'6'</code>（星期六）</td>
</tr>
<tr>
<td align="center">W</td>
<td align="center">ISO-8601周数，周数从星期一开始</td>
<td align="center"><code>1</code>，<code>53</code></td>
</tr>
<tr>
<td align="center">y</td>
<td align="center">年份，2位数字</td>
<td align="center"><code>'99'</code></td>
</tr>
<tr>
<td align="center">Y</td>
<td align="center">年，4位数</td>
<td align="center"><code>'1999年'</code></td>
</tr>
<tr>
<td align="center">z</td>
<td align="center">一年中的日子</td>
<td align="center"><code>0</code>到<code>365</code></td>
</tr>
<tr>
<td align="center">Z</td>
<td align="center">时区偏移量，单位为秒。 UTC以西时区的偏移量总是为负数，对于UTC以东时，它们总是为正</td>
<td align="center"><code>-43200</code>到<code>43200</code></td>
</tr>
</tbody>
</table>
<h4 id="safe">safe</h4>
<p>Django的模板中会对HTML标签和JS等语法标签进行自动转义，原因显而易见，这样是为了安全。但是有的时候我们可能不希望这些HTML元素被转义.
比如我们做一个内容管理系统，后台添加的文章中是经过修饰的，这些修饰可能是通过一个类似于FCKeditor编辑加注了HTML修饰符的文本，如果自动转义的话显示的就是保护HTML标签的源文件。
为了在Django中关闭HTML的自动转义有两种方式，如果是一个单独的变量我们可以通过过滤器<code>|safe</code>的方式告诉Django这段代码是安全的不必转义。</p>
<p>比如：</p>
<pre><code>value = &quot;&lt;a href='#'&gt;点我&lt;/a&gt;&quot;

{{ value|safe}}
</code></pre><h4 id="truncatechars">truncatechars</h4>
<p>如果字符串字符多于指定的字符数量，那么会被截断。截断的字符串将以可翻译的省略号序列（“&hellip;”）结尾。</p>
<p>参数：截断的字符数</p>
<pre><code>{{ value|truncatechars:9}}
</code></pre><h4 id="truncatewords">truncatewords</h4>
<p>在一定数量的字后截断字符串。</p>
<pre><code>{{ value|truncatewords:9}}
</code></pre><h4 id="cut">cut</h4>
<p>移除value中所有的与给出的变量相同的字符串</p>
<pre><code>{{ value|cut:' ' }}
</code></pre><p>如果value为<code>'i love you'</code>，那么将输出<code>'iloveyou'</code>.</p>
<h4 id="join">join</h4>
<p>使用字符串连接列表，例如Python的<code>str.join(list)</code></p>
<h4 id="timesince">timesince</h4>
<p><strong>将日期格式设为自该日期起的时间（例如，4天，6小时）</strong></p>
<p><strong>采用一个可选参数，它是一个包含用作比较点的日期的变量（不带参数，比较点为现在）。 例如，如果blog_date是表示2006年6月1日午夜的日期实例，并且comment_date是2006年6月1日08:00的日期实例，则以下将返回“8小时”：</strong></p>
<pre><code>{{ blog_date|timesince:comment_date }}
</code></pre><p>分钟是所使用的最小单位，对于相对于比较点的未来的任何日期，将返回“0分钟”。</p>
<h4 id="timeuntil">timeuntil</h4>
<p>似于timesince，除了它测量从现在开始直到给定日期或日期时间的时间。 例如，如果今天是2006年6月1日，而conference_date是保留2006年6月29日的日期实例，则</p>
<pre><code>{{ conference_date | timeuntil }}
</code></pre><p>将返回“4周”。</p>
<p>使用可选参数，它是一个包含用作比较点的日期（而不是现在）的变量。 如果from_date包含2006年6月22日，则以下内容将返回“1周”：</p>
<pre><code>{{ conference_date|timeuntil:from_date }}
</code></pre><h4 id="自定义filter">自定义filter</h4>
<p>自定义过滤器只是带有一个或两个参数的Python函数:</p>
<ul>
<li>变量（输入）的值 - -不一定是一个字符串</li>
<li>参数的值 - 这可以有一个默认值，或完全省略</li>
</ul>
<p>例如，在过滤器</p>
<pre><code>{{var | foo:'bar'}}
</code></pre><p>中，过滤器foo将传递变量<code>var</code>和参数<code>bar</code>。</p>
<p>自定义filter代码文件摆放位置：</p>
<pre><code>app01/
    __init__.py
    models.py
    templatetags/  # 在app01下面新建一个package package
        __init__.py
        app01_filters.py  # 建一个存放自定义filter的文件
    views.py
</code></pre><p>编写自定义filter</p>
<pre><code>from django import template
register = template.Library()

@register.filter(name=&quot;cut&quot;)
def cut(value, arg):
    return value.replace(arg, &quot;&quot;)

@register.filter(name=&quot;addSB&quot;)
def add_sb(value):
    return &quot;{} SB&quot;.format(value)
</code></pre><p>使用自定义filter</p>
<pre><code>{# 先导入我们自定义filter那个文件 #}
{% load app01_filters %}

{# 使用我们自定义的filter #}
{{ somevariable|cut:&quot;0&quot; }}
{{ d.name|addSB }}
</code></pre><h3 id="tags">Tags</h3>
<h4 id="for循环">for循环</h4>
<p><strong>普通for循环</strong></p>
<pre><code>&lt;ul&gt;
{% for user in user_list %}
    &lt;li&gt;{{ user.name }}&lt;/li&gt;
{% endfor %}
&lt;/ul&gt;
</code></pre><p>for循环可用的一些参数：</p>
<!-- raw HTML omitted -->
<p><strong>for &hellip; empty</strong></p>
<pre><code>&lt;ul&gt;
{% for user in user_list %}
    &lt;li&gt;{{ user.name }}&lt;/li&gt;
{% empty %}
    &lt;li&gt;空空如也&lt;/li&gt;
{% endfor %}
&lt;/ul&gt;
</code></pre><h4 id="if判断">if判断</h4>
<p><code>if,elif</code>和<code>else</code></p>
<pre><code>{% if user_list %}
  用户人数：{{ user_list|length }}
{% elif black_list %}
  黑名单数：{{ black_list|length }}
{% else %}
  没有用户
{% endif %}
</code></pre><p><strong>当然也可以只有if和else</strong></p>
<pre><code>{% if user_list|length &gt; 5 %}
  七座豪华SUV
{% else %}
    黄包车
{% endif %}
</code></pre><p><strong>if语句支持 and 、or、==、&gt;、&lt;、!=、&lt;=、&gt;=、in、not in、is、is not判断。</strong></p>
<h4 id="with">with</h4>
<p>定义一个中间变量，多用于给一个复杂的变量起别名。</p>
<p>注意等号左右不要加空格。</p>
<pre><code>{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

或

{% with business.employees.count as total %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}
</code></pre><h4 id="csrf_token">csrf_token</h4>
<p>这个标签用于跨站请求伪造保护。</p>
<p>在页面的form表单里面写上</p>
<pre><code>{% csrf_token %}
</code></pre><h4 id="注释">注释</h4>
<pre><code>{# ... #}
</code></pre><h4 id="注意事项">注意事项</h4>
<ol>
<li>Django的模板语言不支持连续判断，即不支持以下写法：</li>
</ol>
<pre><code>{% if a &gt; b &gt; c %}
...
{% endif %}
</code></pre><ol start="2">
<li>Django的模板语言中属性的优先级大于方法</li>
</ol>
<pre><code>def xx(request):
    d = {&quot;a&quot;: 1, &quot;b&quot;: 2, &quot;c&quot;: 3, &quot;items&quot;: &quot;100&quot;}
    return render(request, &quot;xx.html&quot;, {&quot;data&quot;: d})
</code></pre><p>如上，我们在使用render方法渲染一个页面的时候，传的字典d有一个key是items并且还有默认的 <code>d.items()</code> 方法，此时在模板语言中:</p>
<pre><code>{{ data.items }}
</code></pre><p>默认会取d的<code>items key</code>的值。</p>

                
              </div>

              
                <span class="post-meta">
                  
                    #<a href="https://systemime.github.iotags/django/">Django</a>&nbsp;
                  
                    #<a href="https://systemime.github.iotags/%E6%A8%A1%E6%9D%BF/">模板</a>&nbsp;
                  
                </span>
              

            </article>
          
            <article class="post-preview">
              <a href="https://systemime.github.io/blog/2019-05/ubuntu%E5%AE%89%E8%A3%85neo4j%E6%95%B0%E6%8D%AE%E5%BA%93-%E7%9B%B4%E6%8E%A5%E5%AE%89%E8%A3%85%E4%B8%8Edocker%E6%96%B9%E5%BC%8F/">
                <h2 class="post-title">ubuntu安装neo4j数据库-直接安装与docker方式</h2>

                
              </a>

              <p class="post-meta">
                Posted on May 7, 2019
              </p>
              <div class="post-entry">
                
                  <h2 id="添加下载源安装">添加下载源安装</h2>
<pre><code>wget -O - https://debian.neo4j.org/neotechnology.gpg.key | sudo apt-key add -
echo 'deb https://debian.neo4j.org/repo stable/' | sudo tee /etc/apt/sources.list.d/neo4j.list
sudo apt-get update
sudo apt-get install neo4j
</code></pre><h3 id="简单配置">简单配置</h3>
<pre><code>cd /etc/neo4j
vim neo4j.conf
#去掉54行注释
dbms.connectors.default_listen_address=0.0.0.0 

neo4j restart
</code></pre><h3 id="如果报错">如果报错</h3>
<p><strong>注意关闭防火墙</strong></p>
<pre><code>Neo4j not running
Starting Neo4j.
/usr/share/neo4j/bin/neo4j: line 418: /var/run/neo4j/neo4j.pid: No such file or directory
</code></pre><p>解决方案: 创建该目录,重启</p>
<pre><code>mkdir  /var/run/neo4j
neo4j start
 
Active database: graph.db
Directories in use:
  home:         /var/lib/neo4j
  config:       /etc/neo4j
  logs:         /var/log/neo4j
  plugins:      /var/lib/neo4j/plugins
  import:       /var/lib/neo4j/import
  data:         /var/lib/neo4j/data
  certificates: /var/lib/neo4j/certificates
  run:          /var/run/neo4j
Starting Neo4j.
Started neo4j (pid 28360). It is available at http://0.0.0.0:7474/
tr: misaligned [:upper:] and/or [:lower:] construct
There may be a short delay until the server is ready.
See /var/log/neo4j/neo4j.log for current status.
</code></pre><h2 id="docker安装">Docker安装</h2>
<pre><code>docker pull neo4j
docker run -it -d \
    --publish=7474:7474 --publish=7687:7687 \
    --volume=$HOME/neo4j/data:/data \
    neo4j:3.4
</code></pre><h3 id="注意">注意</h3>
<ul>
<li><strong>本机的7474和7687端口注意不要被占用</strong></li>
<li><strong>该容器仅提供服务，其他功能缺失严重，如需其他功能请自行下载linux镜像创建容器，并使用第一步方法安装</strong></li>
</ul>
<h3 id="停止">停止</h3>
<ul>
<li>关闭该容器</li>
<li>进入容器关闭服务</li>
</ul>
<pre><code># 进入启动镜像
docker attach e49d38aec895
# 组合键
Ctrl+C
</code></pre><h3 id="需要进入容器操作">需要进入容器操作</h3>
<pre><code>docker exec -t -i e49d38aec895 /bin/bash
</code></pre><h2 id="neo4j文件夹分布两种方法相同">neo4j文件夹分布（两种方法相同）</h2>
<pre><code>  home:         /var/lib/neo4j
  config:       /etc/neo4j
  logs:         /var/log/neo4j
  plugins:      /var/lib/neo4j/plugins
  import:       /var/lib/neo4j/import
  data:         /var/lib/neo4j/data
  certificates: /var/lib/neo4j/certificates
  run:          /var/run/neo4j
</code></pre>
                
              </div>

              
                <span class="post-meta">
                  
                    #<a href="https://systemime.github.iotags/neo4j/">neo4j</a>&nbsp;
                  
                    #<a href="https://systemime.github.iotags/%E6%95%B0%E6%8D%AE%E5%BA%93/">数据库</a>&nbsp;
                  
                    #<a href="https://systemime.github.iotags/%E5%AE%89%E8%A3%85/">安装</a>&nbsp;
                  
                </span>
              

            </article>
          
        </div>
        
          <ul class="pager main-pager">
            
              <li class="previous">
                <a href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/2">&larr; Newer Posts</a>
              </li>
            
            
              <li class="next">
                <a href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/4">Older Posts &rarr;</a>
              </li>
            
          </ul>
        
      </div>
    <div align="center" class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        

<ul class="pagination">
    
    <li class="page-item">
        <a href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/" class="page-link" aria-label="First"><span aria-hidden="true">&laquo;&laquo;</span></a>
    </li>
    
    <li class="page-item">
    <a href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/2/" class="page-link" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a>
    </li>
    
    
    
    
    
    
    
        
        
    
    
    <li class="page-item"><a class="page-link" href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/">1</a></li>
    
    
    
    
    
    
        
        
    
    
    <li class="page-item"><a class="page-link" href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/2/">2</a></li>
    
    
    
    
    
    
        
        
    
    
    <li class="page-item active"><a class="page-link" href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/3/">3</a></li>
    
    
    
    
    
    
        
        
    
    
    <li class="page-item"><a class="page-link" href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/4/">4</a></li>
    
    
    
    
    
    
        
        
    
    
    <li class="page-item disabled"><span aria-hidden="true">&nbsp;&hellip;&nbsp;</span></li>
    
    
    
    
    
    
        
        
    
    
    
    
    
    
    
        
        
    
    
    
    
    
    
    
        
        
    
    
    
    
    
    
    
        
        
    
    
    
    
    
    
    
        
        
    
    
    
    
    
    
    
        
        
    
    
    <li class="page-item"><a class="page-link" href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/11/">11</a></li>
    
    
    <li class="page-item">
    <a href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/4/" class="page-link" aria-label="Next"><span aria-hidden="true">&raquo;</span></a>
    </li>
    
    <li class="page-item">
        <a href="https://systemime.github.io/series/%E6%9D%82%E6%8A%80%E6%B5%85%E5%B0%9D/page/11/" class="page-link" aria-label="Last"><span aria-hidden="true">&raquo;&raquo;</span></a>
    </li>
    
</ul>


        
        
        
        
        
      </div>
    </div>
  </div>

    <div class="rocket"><img src="https://systemime.github.io/img/rocket_up.png" alt="" width="100" height="100"></div>
<script>
    $(function () {
      $(window).scroll(function () {
        
        if ($(window).scrollTop() >= 1000) {
          $('.rocket').stop().fadeIn(1000);
        }else {
          $('.rocket').stop().fadeOut(1000);
        }
      })
      
      $('.rocket').click(function () {
        $('html,body').stop().animate({scrollTop:0},400);
       
      })
    })

</script>

    
    <div id="landlord">
        <div class="message" style="opacity:0"></div>
        <canvas id="live2d" width="280" height="250" class="live2d"></canvas>
        <div class="hide-button">隐藏</div>
    </div>
    
    <footer id="copyright">
  <div class="container">
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        <ul class="list-inline text-center footer-links">
          
          
        </ul>
        <p class="credits copyright text-muted">
        &copy;2017-2018
          
          &nbsp;&bull;&nbsp;
          September 20,2019
          updated
          
            &nbsp;&bull;&nbsp;
            <a href="https://systemime.github.io">Home</a>
          
        </p>

        <p class="credits theme-by text-muted">
        <a href="https://servicemesher.github.io" target="_blank">ServiceMesher</a>&nbsp;&bull;&nbsp;<a href="https://github.com/yangchuansheng/k8s-knowledge" target="_blank">Kubernetes 知识图谱</a>
        <br />
        <span id="busuanzi_container_site_pv">
            本站已被访问 <span id="busuanzi_value_site_pv"></span> 次啦
        </span>
        <span id="busuanzi_container_site_uv">
            &ensp;|&ensp;&thinsp;您是第 <span id="busuanzi_value_site_uv"></span> 位到访的小伙伴喔
        </span>
        </p>
        
        <p class="credits theme-by text-muted">
          <a href="http://gohugo.io">Hugo v0.67.0</a> powered &nbsp;&bull;&nbsp; Theme by <a href="http://deanattali.com/beautiful-jekyll/">Beautiful Jekyll</a> adapted to <a href="https://github.com/halogenica/beautifulhugo">Beautiful Hugo</a>
          
          <center><section class="credits theme-by text-muted">
    <span class="footer__copyright">
    <div>
    <span id="span_dt_dt"> </span>
    <script language="javascript">
      function show_date_time(){
        window.setTimeout("show_date_time()", 1000);
        BirthDay=new Date("7/8/2017 10:56:12");
        today=new Date();
        timeold=(today.getTime()-BirthDay.getTime());
        sectimeold=timeold/1000
        secondsold=Math.floor(sectimeold);
        msPerDay=24*60*60*1000
        e_daysold=timeold/msPerDay
        daysold=Math.floor(e_daysold);
        e_hrsold=(e_daysold-daysold)*24;
        hrsold=Math.floor(e_hrsold);
        e_minsold=(e_hrsold-hrsold)*60;
        minsold=Math.floor((e_hrsold-hrsold)*60);
        seconds=Math.floor((e_minsold-minsold)*60);
        span_dt_dt.innerHTML="本博客已经开心运行 "+daysold+" 天 "+hrsold+" 小时 "+minsold+" 分 "+seconds+" 秒";
      }
      show_date_time();
    </script>
    </div>
</script>
</section>
</center>
        </p>
      </div>
    </div>
  </div>
</footer>


<script src="https://res.cloudinary.com/jimmysong/raw/upload/rootsongjc-hugo/bootstrap.min.js"></script>
<script src="https://res.cloudinary.com/jimmysong/raw/upload/rootsongjc-hugo/photoswipe-ui-default.min.js"></script>
<script src="https://res.cloudinary.com/jimmysong/raw/upload/rootsongjc-hugo/photoswipe.min.js"></script>
<script src="https://res.cloudinary.com/jimmysong/raw/upload/rootsongjc-hugo/auto-render.min.js"></script>
<script src="https://systemime.github.io/js/main.js"></script>
<script src="https://systemime.github.io/js/clipboard.min.js"></script>
<script src="https://systemime.github.io/js/prism.js?t=123"></script>
<script src="https://systemime.github.io/js/highlight.min.js"></script>
<script src="https://res.cloudinary.com/jimmysong/raw/upload/rootsongjc-hugo/katex.min.js"></script>
<script src="https://systemime.github.io/js/reward.js"></script>
<script src="https://systemime.github.io/js/canvas_ribbon.js"></script>
<script> renderMathInElement(document.body); </script>

<script src="https://systemime.github.io/js/baguetteBox.js"></script>
<script> baguetteBox.run('.gallery');</script>






<script async defer src="https://buttons.github.io/buttons.js"></script>


<script src="https://polyfill.io/v2/polyfill.min.js?features=IntersectionObserver"></script>
<script type="text/javascript" src="https://systemime.github.io/js/quicklink.umd.js"></script>
<script>
window.addEventListener('load', () =>{
   quicklink();
});
</script>



<script type="text/javascript">
 
var a_idx = 0;
jQuery(document).ready(function($) {
    $("body").click(function(e) {
        var a = new Array("Docker", "Kubernetes", "Prometheus", "Envoy", "Istio", "Service Mesh", "Cloud Native");
        var $i = $("<span />").text(a[a_idx]);
        a_idx = (a_idx + 1) % a.length;
        var x = e.pageX,
        y = e.pageY;
        function randomColor() {
          var flakeColor = new Array("#FFDA65", "#00BFFF", "#BA55D3", "#FFA07A", "#87CEEB", "#FFB6C1");
          var snowColor = flakeColor[Math.floor(flakeColor.length * Math.random())];
          return snowColor;
        }
        $i.css({
            "z-index": 999999999999999999999999999999999999999999999999999999999999999999999,
            "top": y - 20,
            "left": x,
            "position": "absolute",
            "font-weight": "bold",
            "color": randomColor()
        });
        $("body").append($i);
        $i.animate({
            "top": y - 180,
            "opacity": 0
        },
        1500,
        function() {
            $i.remove();
        });
    });
});
</script>


<script type="text/javascript" src="https://systemime.github.io/js/lightbox.js"></script>











<script src="https://cdn.plyr.io/3.4.7/plyr.js"></script>
<script>const player = new Plyr('#player');</script>


<script async defer src="https://buttons.github.io/buttons.js"></script>


  </body>
</html>

